import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress'
import { Notification } from 'element-ui'
import Layout from '@/layout'
import Login from '@/views/login'

Vue.use(Router)

const routes = [
  {
    path: '/',
    component: Layout,
    children: []
  },
  {
    path: '/login',
    component: Login
  }
]

// 使用webpack上下文API,递归路由模块,并拼装完整路由配置
const requireContext = require.context('./', true, /\.js$/)
requireContext.keys().forEach(filename => {
  if (filename === './index.js') return
  const routerModule = requireContext(filename)
  routes[0].children = [
    ...routes[0].children,
    ...(routerModule.default || routerModule)
  ]
})

// 导出路由配置
const router = new Router({
  mode: 'history',
  routes
})

// 添加404路由视图
router.addRoute({
  path: '*',
  name: '404',
  component: () => import('@/views/404')
})

// 路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to.matched.some(router => router.meta.auth)) {
    // 去vuex中查找登录信息,如果未登录走下面流程
    const islogin = true
    if (islogin) {
      next()
    } else {
      Notification({
        title: '警告',
        message: '您访问的页面需要登录后才可访问!',
        type: 'warning',
        duration: 2500
      })
      // 跳到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})
router.afterEach((to, from) => {
  console.log('afterEach:', to, from)
  NProgress.done()
})

export default router
